const { Op } = require('sequelize');
const { Users } = require('.././models');
const { NotFounError, success, fail } = require('.././utils/response');
// 查询用户列表处理函数
exports.getusershandle = async (req, res) => {
    // try catch 处理数据
    try {
        const query = req.query
        // 当前是第几页,如果不传默认第一页
        const pageNo = Math.abs(Number(query.pageNo)) || 1
        // 每页显示多少条数据,如果不传,那就是显示10条
        const pageSize = Math.abs(Number(query.pageSize)) || 10
        const offset = (pageNo - 1) * pageSize
        // id倒序
        const condition = {
            // order: [['id', 'DESC']],
            limit: pageSize,
            offset: offset
        }
        const { count, rows } = await Users.findAndCountAll(condition);

        success(res, '查询用户成功!', {
            users: rows,
            paginations: {
                total: count,
                pageNo,
                pageSize
            }
        })
    } catch (error) {
        fail(res, error)
    }

};
// 新增用户处理函数
exports.adduser = async (req, res,) => {
    try {
        // 白名单过滤
        const body = filterBody(req)
        const users = await Users.create(body)
        success(res, "创建用户成功!", { users }, 201)
    } catch (error) {
        fail(res, error)
    }

}
// 更新用户处理函数
exports.updateuser = async (req, res) => {
    try {
        const user = await getuser(req)
        // 白名单过滤
        const body = filterBody(req)
        await user.update(body)
        res.json({
            status: true,
            message: "更新用户成功!",
            data: user
        })
    } catch (error) {
        fail(res, error)
    }

}

/**
 * 公共方法：查询当前用户
 */
async function getuser(req) {
    //获取用户 ID
    const { id } = req.params;
    //查询用户当前用户
    const user = await Users.findByPk(id)
    //如果没有找到,就抛出异常
    if (!user) {
        throw new NotFounError(`ID:${id}的用户没有找到`)
    }
    return user
}

/**
 * 公共方法:白名单id过滤
 * @param {*} req
 * @returns {*}
 * @author ikun
 */
function filterBody(req) {
    return {
        email: req.body.email,
        username: req.body.username,
        password: req.body.password,
        avatar: req.body.avatar,
        role: req.body.role,
        avatar: req.body.avatar,
        introduction: req.body.introduction,
        sex: req.body.sex,
        company: req.body.company,
        nickname: req.body.nickname,
    }
}